<template>
  <div class="obs-study">
    <div class="content">
      <div class="obs_box">
        <div class="obs_box_item">
          <span>功能1:上传图片</span>
          <el-input
            v-model="uploadParams"
            placeholder="请输入图片前缀名称"
          ></el-input>
          <el-upload
            class="upload-demo"
            action
            accept="image/*"
            :http-request="uploadImg"
            :multiple="false"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div class="obs_box_item">
          <span>功能2:上传资源文件</span>
          <el-input
            v-model="uploadParams"
            placeholder="请输入资源文件名称"
          ></el-input>
          <el-upload
            class="upload-demo"
            action
            :http-request="uploadImg"
            :multiple="false"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div class="obs_box_item">
          <span>功能3:返回信息</span>
          <el-button :loading="tableLoading" @click="requestMsg" type="primary"
            >返回信息</el-button
          >
        </div>
        <div class="obs_box_item_table">
          <el-table
            v-loading="tableLoading"
            :data="tableData.dataList"
            border
            style="width: 100%"
          >
            <el-table-column align="center" prop="key_name" label="文件名">
            </el-table-column>
            <el-table-column align="center" label="缩略图">
              <template slot-scope="scope">
                <div
                  class="img_mini"
                  v-if="
                    scope.row.type == 'jpg' ||
                    scope.row.type == 'jpeg' ||
                    scope.row.type == 'png' ||
                    scope.row.type == 'gif' ||
                    scope.row.type == 'pdf'
                  "
                >
                  <img :src="scope.row.url" alt="" />
                </div>
                <div class="img_mini" v-else><span>暂无缩略图</span></div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="time" label="上传时间">
            </el-table-column>
            <el-table-column align="center" prop="size" label="文件大小">
            </el-table-column>
            <el-table-column align="center" prop="type" label="文件类型">
            </el-table-column>
            <el-table-column align="center" width="300" label="文件操作">
              <div slot-scope="scope">
                <div class="handle_box">
                  <span @click="downloadFile(scope.row)">文件下载</span>
                  <span @click="streamDownloadFile(scope.row)">流式下载</span>
                  <span @click="copyAddress(scope.row.url)">复制链接</span>
                  <span @click="deleteFile(scope.row)">删除</span>
                </div>
              </div>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="tableData.pageNum"
            :page-size="tableData.pageSize"
            @size-change="pageSizeChange"
            @current-change="currentChange"
            background
            :page-sizes="[6, 8, 10, 20]"
            layout="total,sizes,prev, pager, next"
            :total="tableData.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  uploadImg,
  getObjectList,
  download,
  streamDownload,
  deleteObj
} from '../api'
import Vue from 'vue'
import { Uploader, Button } from 'vant'
Vue.use(Uploader)
Vue.use(Button)
export default {
  name: 'ObsDemo',
  components: {},
  data () {
    return {
      uploadParams: '',
      tableLoading: false,
      tableData: {
        dataList: [],
        pageSize: 6,
        total: 0,
        pageNum: 1
      },
      bucketName: 'mmangoo-obs'
    }
  },
  filters: {
    src (val) {
      if (!val) { return }
      return `https://mmangoo-obs.obs.cn-east-2.myhuaweicloud.com/${val}?versionId=null`
    }
  },
  mounted () { },
  methods: {
    async uploadImg (params) {
      try {
        const file = params.file
        const fileName = params.file.name
        const type = fileName.slice(
          fileName.lastIndexOf('.') + 1,
          fileName.length
        )
        const formData = new FormData()
        const data = {
          name: this.uploadParams ? this.uploadParams : '',
          type: type
        }
        const param = JSON.stringify(data)
        formData.append('file', file) // 图片文件
        formData.append('data', param) // 图片参数信息
        const res = await uploadImg(formData)
        if (res.data.status === 200) {
          this.$message({
            type: 'success',
            message: `上传成功`
          })
        } else {
          this.$message({
            type: 'warning',
            message: `上传失败`
          })
        }
        this.requestMsg()
      } catch (error) {
        this.$errAlert(error)
      }
    },
    async uploadImgMobile (file) {
      const fileObj = file.file
      const formData = new FormData()
      const data = {
        name: this.uploadParams2,
        id: 10
      }
      const param = JSON.stringify(data)
      formData.append('file', fileObj) // 图片文件
      formData.append('data', param) // 图片参数信息
      this.$errAlert('传输拉')
      try {
        const res = await uploadImg(formData)
        if (res.data.CommonMsg.Status === 200) {
          this.$errAlert('上传成功')
        }
      } catch (error) {
        this.$errAlert(error)
      }
    },
    async requestMsg () {
      this.tableLoading = true
      try {
        const params = {
          bucketName: this.bucketName,
          pageSize: this.tableData.pageSize,
          pageNum: this.tableData.pageNum
        }
        const res = await getObjectList(params)
        this.tableData.total = res.data.total
        this.tableData.dataList = res.data.data
        this.tableLoading = false
      } catch (error) {
        this.tableLoading = false
      }
    },
    async downloadFile (item) {
      this.tableLoading = true
      const type = item.type
      const key = item.key_name
      try {
        const params = {
          bucketName: this.bucketName,
          key: key,
          type: type
        }
        const res = await download(params)
        const content = res.data
        const blob = new Blob([content])
        const fileName = `${key}.${type}`
        const eLink = document.createElement('a')
        eLink.download = fileName
        eLink.style.display = 'none'
        eLink.href = URL.createObjectURL(blob)
        document.body.appendChild(eLink)
        eLink.click()
        URL.revokeObjectURL(eLink.href) // 释放URL 对象
        document.body.removeChild(eLink)
        this.tableLoading = false
      } catch (error) {
        this.$message({
          type: 'fail',
          message: `文件下载失败${error}`
        })
        this.tableLoading = false
        this.requestMsg()
      }
    },
    async streamDownloadFile (item) {
      this.tableLoading = true
      try {
        const type = item.type
        const key = item.key_name
        const params = {
          bucketName: this.bucketName,
          key: key,
          type: type
        }
        const res = await streamDownload(params)
        const content = res.data
        const blob = new Blob([content])
        const fileName = `${key}.${type}`
        const eLink = document.createElement('a')
        eLink.download = fileName
        eLink.style.display = 'none'
        eLink.href = URL.createObjectURL(blob)
        document.body.appendChild(eLink)
        eLink.click()
        URL.revokeObjectURL(eLink.href) // 释放URL 对象
        document.body.removeChild(eLink)
        this.tableLoading = false
      } catch (error) {
        this.$message({
          type: 'fail',
          message: `文件下载失败${error}`
        })
        this.requestMsg()
        this.tableLoading = false
      }
    },
    async deleteFile (item) {
      this.tableLoading = true
      try {
        const params = {
          bucketName: this.bucketName,
          key: item.key_name,
          id: item.id
        }
        const res = await deleteObj(params)
        if (res.data.status === 200) {
          this.$message({
            type: 'success',
            message: `文件删除成功`
          })
          this.requestMsg()
        }
        this.tableLoading = false
      } catch (error) {
        this.$message({
          type: 'fail',
          message: `文件删除失败`
        })
        this.tableLoading = false
        this.requestMsg()
      }
    },
    copyAddress (url) {
      this.$copyText(url)
        .then((res) => {
          this.$message({
            type: 'success',
            message: `文件已复制到剪贴板`
          })
        })['catch']((err) => {
          this.$errAlert(err)
        })
    },
    pageSizeChange (val) {
      this.tableData.pageSize = val
      this.tableData.pageNum = 1
      this.requestMsg()
    },
    currentChange (val) {
      this.tableData.pageNum = val
      this.requestMsg()
    }
  }
}
</script>

<style lang="less" scoped>
.obs-study {
  height: 100%;
}
.handle_box {
  display: flex;
  justify-content: space-around;
  align-items: center;
  span {
    cursor: pointer;
    font-size: 14px;
    &:first-child {
      color: rgb(17, 87, 192);
    }
    &:last-child {
      color: red;
    }
  }
}
@media screen {
  //大于700
  @media (min-width: 700px) {
    .obs_box {
      width: calc(100% - 40px);
      display: flex;
      margin: auto;
      justify-content: space-between;
      flex-wrap: wrap;
      padding: 20px 0;
      .obs_box_item {
        min-width: 300px;
        width: calc((100% - 40px) / 3);
        height: 200px;
        margin-bottom: 20px;
        border: 1px solid #ca2939;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        flex-direction: column;
        justify-content: space-around;
        border-radius: 6px;
      }
      .obs_box_item_table {
        width: 100%;
        margin-bottom: 20px;
        border-radius: 6px;
        text-align: center;
      }
    }
  }
  //小于700
  @media (max-width: 700px) {
    .obs_box {
      width: calc(100% - 20px);
      display: flex;
      margin: auto;
      justify-content: space-between;
      flex-wrap: wrap;
      padding: 20px 0;
      .obs_box_item {
        width: 100%;
        height: 200px;
        margin-bottom: 20px;
        border: 1px solid #ca2939;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        flex-direction: column;
        justify-content: space-around;
        border-radius: 6px;
      }
      .obs_box_item_table {
        width: 100%;
        margin-bottom: 20px;
        border-radius: 6px;
        text-align: center;
      }
    }
  }
}
.img_mini {
  width: 80px;
  height: 80px;
  margin: auto;
  span {
    text-align: center;
    line-height: 80px;
    display: inline-block;
  }
  img {
    width: 100%;
    height: 100%;
  }
}
.upload-demo {
  display: inline-block;
}
.el-input {
  width: 200px;
  margin: 0 20px;
}
</style>
